package 分治.归并排序;

public class 翻转对493 {

    int [] tmp;
    int ret;
    public  int reversePairs(int[] nums)
    {
        int n = nums.length;
        tmp = new int[n];

       return mergeSort(nums,0,n-1);


    }
    public int mergeSort(int [] nums,int left,int right){
        if(left>= right)
            return 0 ;
        int ret = 0;

        // 根据中间元素进行分割
        int mid = (left+right)/2;
        ret += mergeSort(nums,left,mid);
        ret += mergeSort(nums,mid+1,right);

        int cur1 = left,cur2 = mid+1,i=left;
        // 升序
        while(cur2<= right )
        {
           while(cur1 <= mid && nums[cur1]/2.0 <= nums[cur2]) cur1++;
           if(cur1>mid)
               break;
           ret+= mid-cur1+1;
           cur2++;

        }
        //4.合并两个有序数组-升序
        cur1 = left;cur2 = mid+1;
        while(cur1<=mid && cur2<=right)
            tmp[i++] = nums[cur1] <= nums[cur2]?nums[cur1++]:nums[cur2++];
        while(cur1<=mid) tmp[i++] = nums[cur1++];
        while(cur2<= right) tmp[i++] = nums[cur2++];

        for(int j = left; j<=right ; j++)
            nums[j] = tmp[j];

        return ret;




    }

    public static void main(String[] args) {
       int []nums ={1,3,2,3,1};
        翻转对493 z =new 翻转对493();

        int r =z.reversePairs(nums);
        System.out.println(r);
    }
}
